package com.sqly.doc;


import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.adapter.CommonAdapter;
import com.sqly.doc.adapter.ViewHolder;
import com.sqly.doc.menu.qianyue.qianyue_add;
import com.sqly.doc.menu.qianyue.qianyue_view;
import com.sqly.doc.pojo.Doctor;
import com.sqly.doc.pojo.JuMin;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.pojo.ServicePackage;
import com.sqly.doc.util.DateConvert;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.view.StringUtils;
import com.sqly.doc.view.XListView;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.view.PieChartView;

/**
 * 签约界面
 */

@SuppressLint("NewApi")
public class sq_fragment extends Fragment {
    private int[] colorData = {Color.parseColor("#FF4500"),
            Color.parseColor("#87CEFF")};
    private String[] stateChar = {"已签约", "未签约"};
    PieChartView bzfx;
    protected PieChartData pieChardata;
    List<PointValue> v1;

    LinearLayout l1, l2;//内容布局
    ImageView img1, img2, img3;//图表组
    TextView t1, t2, t3;//菜单文字组
    String[] bqcolor;//统计标签列表
    Context con;
    List<ServicePackage> servicelist;//服务包列表数据
    ListView qylistView;//统计如表标签

    private int pageNum1 = 1;// 无关键字页数
    List<JuMin> list;//信息列表
    XListView listView;//居民列表
    String flag = "0";
    ImageView add;
    EditText key;
    List<Doctor> dlist;
    Spinner keynf1, keynf2;
    private List<String> nfdata = new ArrayList<>();
    String nf1= DateConvert.yearofday()+"",nf2=  DateConvert.yearofday()+"";
    ImageView cx1, cx2;//
    TextView nftext1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.sq_fragment, null);
        //实例化控件信息
        initView(view);
        //实例化监听
        initListener();
        gettongji();//获取服务包内容
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void onResume() {
        super.onResume();
        pageNum1 = 1;
        getJumin();
    }

    public void initView(View view) {
        qylistView=(ListView)view.findViewById(R.id.qylistView);
        bzfx=(PieChartView)view.findViewById(R.id.bzfx);
        add = (ImageView) view.findViewById(R.id.add);
        key = (EditText) view.findViewById(R.id.key);
        nftext1 = (TextView) view.findViewById(R.id.nftext1);
        keynf1= (Spinner) view.findViewById(R.id.keynf1);
        keynf2= (Spinner) view.findViewById(R.id.keynf2);
        cx1= (ImageView) view.findViewById(R.id.cx1);
        cx2= (ImageView) view.findViewById(R.id.cx2);
        con = getActivity();
        l1 = (LinearLayout) view.findViewById(R.id.l1);
        l2 = (LinearLayout) view.findViewById(R.id.l2);
        img1 = (ImageView) view.findViewById(R.id.img1);
        img2 = (ImageView) view.findViewById(R.id.img2);
        img3 = (ImageView) view.findViewById(R.id.img3);
        t1 = (TextView) view.findViewById(R.id.tv_wqy);
        t2 = (TextView) view.findViewById(R.id.tv_yqy);
        t3 = (TextView) view.findViewById(R.id.tv_tj);
        listView = (XListView) view.findViewById(R.id.listView);
        listView.setPullLoadEnable(true);

        nftext1.setVisibility(View.GONE);
        keynf1.setVisibility(View.GONE);
        ///签约年限

        for(int i=DateConvert.yearofday()-1; i<=DateConvert.yearofday(); i++) {
            nfdata.add(""+i);
        }
        keynf1.setAdapter(new CommonAdapter<String>(con, nfdata, R.layout.sp_item) {
            @Override
            public void convert(ViewHolder helper, String item) {
                helper.setText(R.id.name, item);
            }
        });
        keynf1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==0){
                    nf1 = ""+(DateConvert.yearofday()-1);
                }else{
                    nf1 = ""+(DateConvert.yearofday()+(position-1));
                }
                System.out.println("nf1=========================>"+nf1);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        keynf1.setSelection(1);

        keynf2.setAdapter(new CommonAdapter<String>(con, nfdata, R.layout.sp_item) {
            @Override
            public void convert(ViewHolder helper, String item) {
                helper.setText(R.id.name, item);
            }
        });
        keynf2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==0){
                    nf2 = ""+(DateConvert.yearofday()-1);
                }else{
                    nf2 = ""+(DateConvert.yearofday()+(position-1));
                }
                System.out.println("nf2=========================>"+nf2);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        keynf2.setSelection(1);

        getJumin();
    }

    public void initListener() {
        key.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        cx1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getJumin();
            }
        });

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!StringUtils.isEmpty(SharedPreferencesUtils.getParam(con, "token", "").toString())) {
                    Bundle b = new Bundle();
                    b.putSerializable("j", null);
                    startActivity(new Intent(getActivity(), qianyue_add.class).putExtras(b));
                }
            }
        });
        t1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                t1.setTextColor(Color.parseColor("#008B8B"));
                img1.setImageResource(R.mipmap.myqy2);
                t2.setTextColor(Color.parseColor("#8A8A8A"));
                img2.setImageResource(R.mipmap.yjqy1);
                t3.setTextColor(Color.parseColor("#8A8A8A"));
                img3.setImageResource(R.mipmap.tj2);
                l1.setVisibility(View.VISIBLE);
                l2.setVisibility(View.GONE);
                nftext1.setVisibility(View.GONE);
                keynf1.setVisibility(View.GONE);
                pageNum1 = 1;
                flag = "0";
                getJumin();
            }
        });
        t2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                t2.setTextColor(Color.parseColor("#008B8B"));
                img1.setImageResource(R.mipmap.myqy1);
                t1.setTextColor(Color.parseColor("#8A8A8A"));
                img2.setImageResource(R.mipmap.yjqy2);
                t3.setTextColor(Color.parseColor("#8A8A8A"));
                img3.setImageResource(R.mipmap.tj2);
                l1.setVisibility(View.VISIBLE);
                l2.setVisibility(View.GONE);
                nftext1.setVisibility(View.VISIBLE);
                keynf1.setVisibility(View.VISIBLE);
                pageNum1 = 1;
                flag = "1";
                getJumin();
            }
        });
        t3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                t3.setTextColor(Color.parseColor("#008B8B"));
                img1.setImageResource(R.mipmap.myqy1);
                t1.setTextColor(Color.parseColor("#8A8A8A"));
                img2.setImageResource(R.mipmap.yjqy1);
                t2.setTextColor(Color.parseColor("#8A8A8A"));
                img3.setImageResource(R.mipmap.tj1);
                l1.setVisibility(View.GONE);
                l2.setVisibility(View.VISIBLE);
                gettongji();
                getQyDoc();
            }
        });

        cx2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gettongji();
                getQyDoc();
            }
        });
    }

    //获取签约居民的信息

    public void getJumin() {
        if (!NetWorkUtils.isNetworkConnected(con)) {
            if (flag.equals("0")) {
                if(StringUtils.isEmpty(key.getText().toString())) {
                    list = DataSupport.where("issign=1").find(JuMin.class);
                }else{
                    list = DataSupport.where("issign=1 and XINGMING like %"+key.getText().toString()+"% or CARDNUM=?",key.getText().toString()).find(JuMin.class);
                }
            } else {
                if(StringUtils.isEmpty(key.getText().toString())) {
                    list = DataSupport.where("issign=2").find(JuMin.class);
                }else{
                    list = DataSupport.where("issign=2 and XINGMING like %"+key.getText().toString()+"% or CARDNUM=?",key.getText().toString()).find(JuMin.class);
                }
            }
            listView.setXListViewListener(new XListView.IXListViewListener() {
                @Override
                public void onRefresh() {
                    key.setText("");
                    if (flag.equals("0"))
                        list = DataSupport.where("issign=1").find(JuMin.class);
                    else
                        list = DataSupport.where("issign=2").find(JuMin.class);
                    listView.setAdapter(new CommonAdapter<JuMin>(con, list, R.layout.jumin_item) {
                        @Override
                        public void convert(ViewHolder helper, JuMin item) {
                            helper.setText(R.id.number, item.getJKDAH());
                            helper.setText(R.id.name, item.getXINGMING());
                            helper.setText(R.id.cardnum, item.getCARDNUM());
                        }
                    });
                }
                @Override
                public void onLoadMore() {

                }
            });
            listView.setAdapter(new CommonAdapter<JuMin>(con, list, R.layout.jumin_item) {
                @Override
                public void convert(ViewHolder helper, JuMin item) {
                    helper.setText(R.id.number, item.getJKDAH());
                    helper.setText(R.id.name, item.getXINGMING());
                    helper.setText(R.id.cardnum, item.getCARDNUM());
                }
            });
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Bundle b = new Bundle();
                    b.putSerializable("j", list.get(position - 1));
                    if(flag.equals("0")){
                        //未签约
                        System.out.println("未签约=========================================");
                    }else{
                        //已签约
                        System.out.println("已签约------------------------------");
                    }
                    startActivity(new Intent(con, qianyue_add.class).putExtras(b));
                }
            });
        } else {
            RequestParams ps = new RequestParams();
            ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
            ps.add("type", "2");
            ps.add("page", pageNum1 + "");
            ps.add("flag", flag);
            if (!StringUtils.isEmpty(key.getText().toString())) {
                ps.add("XINGMING", key.getText().toString());
            }
            if (!StringUtils.isEmpty(nf1)) {
                ps.add("nf", nf1);
            }

            UserClient.get(HttpUrl.GetSignedUser, ps, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                    MyToastUtil.ShowToast(con, "请求失败");
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                    String content = new String(response);
                    RetMsg ret = JSON.parseObject(content, RetMsg.class);
                    if (ret.getCode().equals("200")) {
                        if (pageNum1 == 1)
                            list = new ArrayList<JuMin>();
                        List<JuMin> ll = JSON.parseArray(
                                ret.getList(), JuMin.class);
                        for (int i = 0; i < ll.size(); i++) {
                            list.add(ll.get(i));
                        }
                        listView.setSelection(list.size() - ll.size());
                        listView.stopRefresh();
                        listView.stopLoadMore();
                        listView.setRefreshTime("刚刚");
                        listView.setXListViewListener(new XListView.IXListViewListener() {
                            @Override
                            public void onRefresh() {
                                pageNum1 = 1;
                                getJumin();
                            }

                            @Override
                            public void onLoadMore() {
                                pageNum1 = pageNum1 + 1;
                                getJumin();
                            }
                        });
                        listView.setAdapter(new CommonAdapter<JuMin>(con, list, R.layout.jumin_item) {
                            @Override
                            public void convert(ViewHolder helper, JuMin item) {
                                helper.setText(R.id.name, item.getXINGMING());
                                helper.setText(R.id.cardnum, item.getCARDNUM());
                                helper.setText(R.id.number, DateConvert.dateToString(DateConvert.toDate(item.getCSRQ(), DateConvert.YMD), DateConvert.YMD)+"    ");
                            }
                        });
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                if(flag.equals("0")){
                                    //未签约
                                    System.out.println("未签约2=========================================");
                                    Bundle b = new Bundle();
                                    b.putSerializable("j", list.get(position - 1));
                                    startActivity(new Intent(con, qianyue_add.class).putExtras(b));
                                }else{
                                    //已签约
                                    System.out.println("已签约2------------------------------");

                                    Bundle b = new Bundle();
                                    b.putSerializable("j", list.get(position - 1));
                                    startActivity(new Intent(con, qianyue_view.class).putExtras(b));
                                }

                            }
                        });

                        for (int i = 0; i < ll.size(); i++) {
                            List<JuMin> jlist = DataSupport.where("SFZH = ?", ll.get(i).getSFZH()).find(JuMin.class);
                            if (jlist.size() > 0) {
                                if (flag.equals("0"))
                                    jlist.get(0).setIssign("1");//沒有签约
                                else
                                    jlist.get(0).setIssign("2");//已经签约
                                jlist.get(0).update(jlist.get(0).getId());
                            } else {
                                Log.i("居民数据", "直接插入的数据");
                                ll.get(i).setIsupdate("1");//设置不需要更新的操作
                                if (flag.equals("0"))
                                    ll.get(i).setIssign("1");//沒有签约
                                else
                                    ll.get(i).setIssign("2");//已经签约
                                ll.get(i).save();
                            }
                        }
                    } else {
                        MyToastUtil.ShowToast(con, "获取错误");
                    }
                }

            });
        }
    }
    //获取统计信息
    public void gettongji() {
      RequestParams ps=new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(getActivity(),"token","").toString());
        ps.add("type","2");
        if (!StringUtils.isEmpty(nf2)) {
            ps.add("nf", nf2);
        }
        UserClient.get(HttpUrl.GetQyTj,ps,new AsyncHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                JSONArray j=JSON.parseArray(ret.getRd());
                JSONObject js=j.getJSONObject(0);
                List<SliceValue> values = new ArrayList<SliceValue>();
                    SliceValue sliceValue1 = new SliceValue(Float.parseFloat(js.getString("qySum")), colorData[0]);
                    values.add(sliceValue1);
                SliceValue sliceValue2 = new SliceValue(Float.parseFloat(js.getString("wqySum")), colorData[1]);
                values.add(sliceValue2);
                pieChardata = new PieChartData();
                pieChardata.setHasLabels(true);//显示表情
                pieChardata.setHasLabelsOnlyForSelected(false);//不用点击显示占的百分比
                pieChardata.setHasLabelsOutside(false);//占的百分比是否显示在饼图外面
                pieChardata.setHasCenterCircle(true);//是否是环形显示
                pieChardata.setValues(values);//填充数据
                pieChardata.setCenterCircleColor(Color.WHITE);//设置环形中间的颜色
                pieChardata.setCenterCircleScale(0.5f);//设置环形的大小级别
                bzfx.setPieChartData(pieChardata);
                bzfx.setValueSelectionEnabled(true);//选择饼图某一块变大
                bzfx.setAlpha(0.9f);//设置透明度
                bzfx.setCircleFillRatio(1f);//设置饼图大小

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }
    public void getQyDoc(){
        RequestParams ps=new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(getActivity(),"token","").toString());
        ps.add("type","2");
        if (!StringUtils.isEmpty(nf2)) {
            ps.add("nf", nf2);
        }
        UserClient.get(HttpUrl.GetQyByDoc,ps,new AsyncHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                dlist=JSON.parseArray(ret.getRd(),Doctor.class);
                qylistView.setAdapter(new CommonAdapter<Doctor>(getActivity(),dlist,R.layout.doctor_item) {
                    @Override
                    public void convert(ViewHolder helper, Doctor item) {
                        helper.setText(R.id.name,item.getNickNameD());
                        helper.setText(R.id.gzdw,item.getNameD());
                        helper.setText(R.id.tjrs,item.getYqyrs());
                    }
                });

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }
}
